from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, 
                               QTableWidgetItem, QLineEdit, QLabel, QComboBox,
                               QHeaderView, QPushButton, QMessageBox)
from PySide6.QtCore import Qt
from PySide6.QtGui import QFont, QColor, QPainter, QPen, QBrush

from database.db_manager import DBManager

class WordListWidget(QWidget):
    """单词列表界面，用于展示、搜索和筛选单词"""
    
    def __init__(self, db_manager: DBManager, parent=None):
        super().__init__(parent)
        self.db_manager = db_manager
        self.init_ui()
        
    def init_ui(self):
        """初始化UI组件"""
        layout = QVBoxLayout(self)
        
        # 创建搜索和筛选控件
        filter_layout = QHBoxLayout()
        filter_layout.setContentsMargins(10, 10, 10, 10)
        
        # 搜索框
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("搜索单词...")
        self.search_edit.textChanged.connect(self.filter_words)
        self.search_edit.setMinimumHeight(35)
        
        # 筛选下拉框
        self.filter_combo = QComboBox()
        self.filter_combo.addItems(["所有单词", "未学习", "学习中", "已掌握"])
        self.filter_combo.currentIndexChanged.connect(self.filter_words)
        self.filter_combo.setMinimumHeight(35)
        
        # 添加到布局
        filter_layout.addWidget(QLabel("搜索:"))
        filter_layout.addWidget(self.search_edit)
        filter_layout.addSpacing(20)
        filter_layout.addWidget(QLabel("筛选:"))
        filter_layout.addWidget(self.filter_combo)
        filter_layout.addStretch()
        
        layout.addLayout(filter_layout)
        
        # 创建单词表格
        self.table = QTableWidget()
        self.table.setColumnCount(6)
        self.table.setHorizontalHeaderLabels(["单词", "音标", "释义", "掌握程度", "复习次数", "上次复习"])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.verticalHeader().setVisible(False)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setMinimumHeight(400)
        
        layout.addWidget(self.table)
        
        # 添加状态栏
        self.status_label = QLabel()
        layout.addWidget(self.status_label)
        
        # 初始加载数据
        self.refresh_data()
        
    def refresh_data(self):
        """从数据库刷新单词列表数据"""
        # 获取所有单词
        conn = self.db_manager._connect()
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM words ORDER BY word ASC')
        rows = cursor.fetchall()
        conn.close()
        
        # 更新表格
        self.table.setRowCount(len(rows))
        for row_idx, row in enumerate(rows):
            # 单词
            word_item = QTableWidgetItem(row['word'])
            word_item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row_idx, 0, word_item)
            
            # 音标
            phonetic_item = QTableWidgetItem(row['phonetic'] or "")
            phonetic_item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row_idx, 1, phonetic_item)
            
            # 释义（截取部分显示）
            meaning = row['meaning'][:50] + "..." if len(row['meaning']) > 50 else row['meaning']
            meaning_item = QTableWidgetItem(meaning)
            self.table.setItem(row_idx, 2, meaning_item)
            
            # 掌握程度
            mastery_levels = ["未学习", "学习中", "已掌握"]
            mastery_text = mastery_levels[row['mastery_level']] if row['mastery_level'] < 3 else "未学习"
            
            mastery_item = QTableWidgetItem(mastery_text)
            mastery_item.setTextAlignment(Qt.AlignCenter)
            
            # 设置不同掌握程度的颜色
            colors = [QColor(255, 59, 48), QColor(255, 204, 0), QColor(52, 199, 89)]
            if row['mastery_level'] < 3:
                mastery_item.setBackground(colors[row['mastery_level']])
                mastery_item.setForeground(QColor(255, 255, 255) if row['mastery_level'] != 1 else QColor(0, 0, 0))
                
            self.table.setItem(row_idx, 3, mastery_item)
            
            # 复习次数
            review_item = QTableWidgetItem(str(row['review_count']))
            review_item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row_idx, 4, review_item)
            
            # 上次复习时间
            last_review = row['last_review'] or "从未"
            review_item = QTableWidgetItem(last_review)
            review_item.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(row_idx, 5, review_item)
            
        # 更新状态栏
        self.status_label.setText(f"共 {len(rows)} 个单词")
        
    def filter_words(self):
        """根据搜索框和筛选条件过滤单词列表"""
        search_text = self.search_edit.text().lower()
        filter_index = self.filter_combo.currentIndex()
        
        for row_idx in range(self.table.rowCount()):
            # 获取当前行数据
            word_item = self.table.item(row_idx, 0)
            mastery_item = self.table.item(row_idx, 3)
            
            if not word_item or not mastery_item:
                self.table.setRowHidden(row_idx, True)
                continue
                
            # 搜索文本匹配
            word_match = search_text in word_item.text().lower()
            
            # 筛选条件匹配
            filter_match = True
            if filter_index == 1:  # 未学习
                filter_match = mastery_item.text() == "未学习"
            elif filter_index == 2:  # 学习中
                filter_match = mastery_item.text() == "学习中"
            elif filter_index == 3:  # 已掌握
                filter_match = mastery_item.text() == "已掌握"
                
            # 显示或隐藏行
            self.table.setRowHidden(row_idx, not (word_match and filter_match))